/*
 * Copyright (C) 2021  AniTrend
 *
 *     This program is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     This program is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package co.anitrend.core.android.storage.extensions

import java.util.*
import kotlin.math.ln
import kotlin.math.pow

fun Float.toHumanReadableByteValue(si: Boolean = false): String {
    val bytes = this
    val unit = if (si) 1000 else 1024
    if (bytes < unit) return "$bytes B"
    val exp =
        (ln(bytes.toDouble()) / ln(unit.toDouble())).toInt()
    val pre =
        (if (si) "kMGTPE" else "KMGTPE")[exp - 1].toString() + if (si) "" else "i"
    return String.format(
        Locale.getDefault(), "%.1f %sB",
        bytes / unit.toDouble().pow(exp.toDouble()), pre
    )
}

fun Long.toHumanReadableByteValue(si: Boolean = false): String {
    val bytes = this
    val unit = if (si) 1000 else 1024
    if (bytes < unit) return "$bytes B"
    val exp =
        (ln(bytes.toDouble()) / ln(unit.toDouble())).toInt()
    val pre =
        (if (si) "kMGTPE" else "KMGTPE")[exp - 1].toString() + if (si) "" else "i"
    return String.format(
        Locale.getDefault(), "%.1f %sB",
        bytes / unit.toDouble().pow(exp.toDouble()), pre
    )
}